import Taro, {Component} from '@tarojs/taro'
import {View, Image, Text} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import * as productActions from '../../actions/product'
import * as wxActions from '../../actions/wx'
import {getNavSize} from '../../utils/style'
import {parseTime, s_to_hs, strToDate} from '../../utils/comman'
import './index.scss'
// AtList,AtListItem,,AtFloatLayout,AtDivider
import {AtTag, AtFloatLayout} from 'taro-ui'
import Fix from '../../components/Fix'
import classNames from 'classnames'
import Navbar from "../../components/Navbar";
import downLoad from '../../utils/download'
import {isH5} from '../../utils/platform'

export const PRODUCT_PRAMS = 'PRODUCT_PRAMS'//参数
export const PRODUCT_COVERY = 'PRODUCT_COVERY'//包邮
export const PRODUCT_SUCAI = 'PRODUCT_SUCAI'//素材

@connect(state => ({...state.product, ...state.wx}), {...productActions, ...wxActions})
class Detail extends Component {
  state = {
    id: null,
    loading: true,
    isVisible: false,
    FloatLayout: '',
    navHeight: 0,
    showNavBar: true
  }

  static options = {
    addGlobalClass: true,
  }

  config = {
    navigationBarTitleText: '商品详情',
    enablePullDownRefresh: true,
    navigationStyle: "custom",
    usingComponents: {
      'i-spin': '../../wxComponents/spin/index', // 书写第三方组件的相对路径
    },
  }

  onShareAppMessage() {
    const {path, params} = this.$router
    let shareObj = {
      title: this.props.productInfo.name,
      path: path + '?id=' + params.id,
      // imageUrl:imagePath,
      imageUrl: this.props.productInfo.bannerImage.url,
    }
    return shareObj
  }


  onShareTimeline() {
    return {
      title: this.props.productInfo.name,
      path: path + '?id=' + params.id,
      imageUrl: this.props.productInfo.bannerImage.url,
    }
  }


  componentWillMount() {
    this.props.dispatchProductClear()
    const {id} = this.$router.params
    this.setState({
      id,
      loading: true
    })
  }

  /**
   * 预览图片
   */
  previewImages(item) {
    var current = item.url;
    Taro.previewImage({
      current: current.replace(DETAIL_SPLIT, QIANYOUZHUO_SPLIT), // 当前显示图片的http链接
      urls: this.props.productInfo.files.map(item => item.url.replace(DETAIL_SPLIT, QIANYOUZHUO_SPLIT)) // 需要预览的图片http链接列表
    })
  }

  previewImage(url) {
    Taro.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  }

  componentDidMount() {

  }

  componentDidShow() {
    this.props.dispatchProductInfo({id: this.state.id}).then(res => {
      this.setState({
        loading: false
      })
    })
    const {statusHeight, navHeight} = getNavSize()
    this.setState({
      navHeight: statusHeight + navHeight
    })
  }

  onPullDownRefresh() {
    this.props.dispatchProductInfo({id: this.state.id}).then(res => {
      this.setState({
        loading: false
      })
      Taro.stopPullDownRefresh()
    })
  }

  openFloatLayout(key) {
    this.setState({
      FloatLayout: key,
      isVisible: true
    })
  }

  cloesFloatLayout() {
    this.setState({
      isVisible: false,
      FloatLayout: ''
    })
  }


  seeVideo() {
    Taro.navigateTo({
      url: `/pages/video/index`
    })
  }


  share() {
    const {id} = this.state
    const {path} = this.$router
    const {bannerImage, name} = this.props.productInfo
    console.log(`/pages/share/index?title=${name}&id=${id}&bannerImage=${bannerImage.url}&url=${path}`)
    Taro.navigateTo({
      url: `/pages/share/index?title=${name}&id=${id}&bannerImage=${bannerImage.url}&url=${path}`
    })
  }


  like(result) {
    const token = Taro.getStorageSync('token')
    if (token) {
      const {id} = this.state
      if (result) {
        this.props.dispatchProductLikeCancel({id})
      } else {
        this.props.dispatchProductLikeAdd({id})
      }
    } else {
      // `/pages/detail/index?id=${id}&name=${name}`
      // const {id} = this.state
      // const {name} = this.props.productInfo
      Taro.navigateTo({
        url: `/pages/auth/index`
      })
    }
  }


  sucai() {
    this.setState({
      FloatLayout: PRODUCT_SUCAI,
      isVisible: true
    })
  }

  copy(text) {
    this.setState({
      isVisible: false
    })
    Taro.setClipboardData({
      data: text
    }).then(res => {
      Taro.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }).catch(err => {
      Taro.showToast({
        title: '复制失败'
      });
    })
  }

  saveImages(files) {
    this.setState({
      isVisible: false
    })
    const sucaiFiles = files instanceof Array ? files.map(item => {
      item.url = item.url.replace(DETAIL_SPLIT, QIANYOUZHUO_SPLIT)
      return item
    }) : []
    downLoad(sucaiFiles)
  }

  saveVideo(video) {
    this.setState({
      isVisible: false
    })
    // HOST+item.video.staticFilePath
    if (!video.staticFilePath) {
      Taro.showToast({
        title: '该商品无视频实拍',
        duration: 1000
      })
      return;
    }
    // downLoad(HOST + video.staticFilePath,'video')
    downLoad(video.url, 'video')
  }

  componentDidHide() {

  }

  componentWillUnmount() {

  }

  componentCatchError() {
  }

  modify() {
    const {params} = this.$router
    if (!params.id) return
    Taro.navigateTo({
      url: `/pages/operate/index?id=${params.id}`
    })
  }

  render() {
    const {loading, isVisible, FloatLayout, navHeight, showNavBar} = this.state
    let pt = navHeight + 'px'
    if (!showNavBar) {
      pt = 0 + 'px'
    }
    let {bannerImage, name, files, summary, video, tags, createTime, viewCount} = this.props.productInfo
    let FloatLayoutTitle = ''
    if (FloatLayout == PRODUCT_PRAMS) {
      FloatLayoutTitle = '产品参数'
    }
    if (FloatLayout == PRODUCT_COVERY) {
      FloatLayoutTitle = '不发货地区'
    }
    if (FloatLayout == PRODUCT_SUCAI) {
      FloatLayoutTitle = '素材'
    }
    const {path, params} = this.$router
    const token = Taro.getStorageSync('token')
    const {userInfo} = this.props
    const content = (
      <View className={classNames('detail_page-content', {'detail_page-h5-content': isH5()})}>

        <View className="detail__page-header">
          <View className="detail__page-banner">
            {/* <CoverView className="detail__page-banner-cover-video"> */}
            {/*
              {
                video.url &&(
                  <Video id='video'
                      className="detail__page-banner-video"
                      controls={true}
                      autoplay={false}
                      showPlayBtn={true}
                      playBtnPosition="center"
                      showFullscreenBtn={true}
                      showCenterPlayBtn={true}
                      showProgress={true}
                      showMuteBtn={true}
                      src={video.url}
                      muted={false}
                      objectFit="contain"
                      loop={false}
                      initialTime={0}
                      custom-cache={false}
                    ></Video>
                )
              } */}
            {/* <View className="detail_video"  onClick={this.play.bind(this)}>
                      <Text className="at-icon at-icon-play detail_play"></Text>
                      <Image src={item.video.url+VIDEO_SUFFIX}
                      mode="aspectFill" className="detail__page-banner-img"></Image>
                    </View> */}
            {/* {
                !video.url &&
                <Image src={files.length>0?files[0].url:bannerImage.url}
                  onClick={this.previewImage.bind(this,files.length>0?files[0].url:bannerImage.url)}
                mode="aspectFill" className="detail__page-banner-img"></Image>
              } */}
            {
              video && !video.url &&
              <Image src={bannerImage ? bannerImage.url : ''} lazyLoad
                     style={{width: Taro.pxTransform(200)}}
                     onClick={this.previewImage.bind(this, bannerImage ? bannerImage.url.replace(LOGO_SPLIT, QIANYOUZHUO_SPLIT) : '')}
                     mode="widthFix" className="detail__page-banner-img" webp></Image>
            }
            {
              video && video.url &&
              <View key={video.hash}
                    className={classNames('recommend_box_vedio_item')}
                    onClick={this.seeVideo.bind(this)}
              >
                <Image
                  className="recommend_box_vedio_item-img"
                  src={video.url + VIDEO_SUFFIX}
                  mode="widthFix"
                  lazyLoad
                  webp
                  style={{width: Taro.pxTransform(200)}}
                />
                <View className="recommend_box_vedio_item-button">
                  <Text className="at-icon at-icon-play">

                  </Text>
                  <Text>
                    {s_to_hs(video.avinfo ? video.avinfo.video.duration : 0)}
                  </Text>
                </View>
              </View>
            }
          </View>
          <View className="detail__page-header-right">
            <View>
              <Text className="detail__page-title">
                {name}
              </Text>
              <Text className="detail__page-time">
                <Text className="detail__page-label">上架日期：</Text>
                {
                  parseTime(strToDate(createTime))
                }
              </Text>
              <Text className="detail__page-read">
                {viewCount}浏览
              </Text>
            </View>
            {
              tags && tags.length > 0 ?
                <View className="detail__page-tags">
                  {
                    tags.map((tag) => (
                      <AtTag
                        size="normal"
                        className="detail__page-tags-item"
                        type='primary'
                        active
                      >
                        {tag}
                      </AtTag>
                    ))
                  }
                </View>
                : null
            }
          </View>
        </View>


        {/* <View className="detail__page-list">
          <AtList>
              <AtListItem title='运费' note='除了顺丰均包邮'/>
              <AtListItem title='注意事项' note="不发货地区" arrow='right' onClick={this.openFloatLayout.bind(this,PRODUCT_COVERY)}/>
          </AtList>
        </View> */}
        {/* <AtListItem title='参数' note="规格材质等" arrow='right' onClick={this.openFloatLayout.bind(this,PRODUCT_PRAMS)}/> */}

        {/* <View className="custom-shuiyin">
          <AtIcon prefixClass='icon' value='weixinfill' color='#333333'></AtIcon>
          <Text className="custom-shuiyin-icon">qq95476020</Text>
        </View> */}
        <Text className="detail__page-detail-header detail__page-detail-header-px" decode={true}>
          详情
        </Text>
        {
          summary ?
            <View className="detail__page-summary">
              {/* <AtDivider content='商品描述' /> */}
              <Text className="detail-summary-text" space="ensp" decode={true}>
                {summary}
              </Text>
            </View>
            : null
        }
      </View>)
    return (
      // style={{'height':'100%'}}
      <View className="detail__page" style={{'padding-top': pt}}>
        {
          showNavBar && <Navbar type="icon" fixed={true}></Navbar>
        }
        {/* { */}
        {/* loading?<Loading spinning={loading}> </Loading>:content */}
        {/* } */}
        {/* <Loading spinning={loading}> */}
        {/* </Loading> */}
        <View className="detail_page-wrapper">
          {
            <Fix
              placement="top"
              showHaibao={true}
              onShare={this.share.bind(this)}
              showHeart={true}
              showSucai={true}
              onHandleLike={this.like.bind(this)}
              onHandleSucai={this.sucai.bind(this)}
              showMessageCard={true}
              sendMessageImg={bannerImage ? bannerImage.url : ''}
              sendMessagePath={path + '?id=' + params.id}
              sendMessageTitle={name}
              showModify={true}
              onModify={this.modify.bind(this)}
            >
              {/*&& token && userInfo && userInfo.role == 1*/}
            </Fix>
          }
          {
            content
          }
          <View className="detail__page-detail">
            {/* <AtDivider content='商品详情' /> */}
            {/* <View className="detail__page-detail-imgs">
                  {
                    files.length>0?
                    files.map((item,index)=>(
                      <Image src={item.url} key={index} mode="widthFix" className="detail__page-detail-img" lazyLoad={true}
                      onClick={this.previewImages.bind(this,item)}></Image>
                    )):null
                  }
              </View> */}
            <Text className="detail__page-detail-header detail__page-detail-header-px" decode={true}>
              组图
            </Text>
            {/* <ScrollView scrollX={true} className="detail__page-detail-imgs">
                  {
                    files.length>0?
                    files.map((item,index)=>(
                      <Image src={item.url} key={index} mode="aspectFill" className="detail__page-detail-img" lazyLoad={true}
                      onClick={this.previewImages.bind(this,item)}></Image>
                    )):null
                  }
              </ScrollView> */}
            <View className="like_page_row">
              {
                files && files.length > 0 ?
                  files.map((item, index) => (
                    <View className="like_page_col">
                      <View className="like_page_item" onClick={this.previewImages.bind(this, item)}>
                        {/* <Text className="like_page_count">{item.url}</Text> */}
                        <View className="like_page_item_item">
                          <Image mode="scaleToFill" src={item.url} className="like_page_image" lazyLoad={true}
                                 webp></Image>
                        </View>
                      </View>
                    </View>
                  )) : null
              }
            </View>
          </View>
          {
            loading && <i-spin fix size="large" fullscreen></i-spin>
          }
          <View
            className={classNames({'float-layout-wrapper1': FloatLayout == PRODUCT_COVERY}, {'float-layout-wrapper2': FloatLayout == PRODUCT_PRAMS},
              {'float-layout-wrapper3': FloatLayout == PRODUCT_SUCAI})}>
            <AtFloatLayout isOpened={isVisible} title={FloatLayoutTitle} onClose={this.cloesFloatLayout.bind(this)}>
              {/* {
                    FloatLayout == PRODUCT_COVERY?
                    <View className="float-layout">
                      <View>
                        暂无不发货地区
                      </View>
                      <View>
                        <AtButton type='primary' onClick={this.cloesFloatLayout.bind(this)} circle>关闭</AtButton>
                      </View>
                  </View>:null
                } */}
              {/* {
                    FloatLayout == PRODUCT_SUCAI?
                    <View className="float-layout">
                          {
                            sucaiFiles.length>0?
                            <View className="like_page_row">
                              {
                                sucaiFiles.map(item=>(
                                  <View className="like_page_col">
                                      <View className="like_page_item">
                                          <View className="like_page_item_item">
                                              <Image mode="scaleToFill" src={item.url} className="like_page_image"></Image>
                                          </View>
                                      </View>
                                  </View>
                                ))
                              }
                            </View>
                            :<View>暂无素材图片</View>
                          }
                      <View>
                        <AtButton type='primary' onClick={this.cloesFloatLayout.bind(this)} circle>批量下載</AtButton>
                      </View>
                  </View>:null
                } */}
              {
                FloatLayout == PRODUCT_PRAMS ?
                  <View className="detail-params-list">
                    <View className="detail-params-list-item">
                      <View className="detail-params-list-item-left">
                        规格
                      </View>
                      <View className="detail-params-list-item-right">
                        {productInfo.size ? productInfo.size : ''}
                      </View>
                    </View>
                    <View className="detail-params-list-item">
                      <View className="detail-params-list-item-left">
                        材质
                      </View>
                      <View className="detail-params-list-item-right">
                        {productInfo.material ? productInfo.material : ''}
                      </View>
                    </View>
                  </View> : null
              }
              {
                FloatLayout == PRODUCT_SUCAI ?
                  <View className="detail_modal_body">
                    <View className="detail_modal_item" onClick={this.copy.bind(this, name + summary)}>
                      {/* <Image
                        className="detail_modal_image"
                        src={fuzhitupian}
                        mode="aspectFit"
                      /> */}
                      <View className="icon icon-fuzhi"></View>
                      <View className="detail_modal_desc">
                        <View>复制朋友圈文案</View>
                      </View>
                    </View>
                    <View className="detail_modal_item" onClick={this.saveImages.bind(this, files)}>
                      {/* <Image
                        className="detail_modal_image"
                        src={tupiantupian}
                        mode="aspectFit"
                      /> */}
                      <View className="icon icon-tupian"></View>
                      <View className="detail_modal_desc">
                        <View>下载素材图片</View>
                      </View>
                    </View>
                    <View className="detail_modal_item" onClick={this.saveVideo.bind(this, video)}>
                      {/* <Image
                        className="detail_modal_image"
                        src={shipintupian}
                        mode="aspectFit"
                      /> */}
                      <View className="icon icon-shipin"></View>
                      <View className="detail_modal_desc">
                        <View>下载实拍视频</View>
                      </View>
                    </View>
                  </View> : null
              }
            </AtFloatLayout>
          </View>
        </View>

      </View>
    )
  }
}

export default Detail

